<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Components\UserComponent;
use App\Http\Components\RongCloudComponent;

use DB;
use App\Models\UserModel;
use App\Models\UserAccountModel;
use App\Models\UserProfileModel;
use App\Models\UserSettingModel;

use App\Models\UserLogModel;
/**
 * 用户登录
 */
class LoginAuthController extends UserController{

    public function __construct(){
        parent::__construct();
    }

    /*版本控制，对应app版本跳转对应接口*/
    public function version_invoke(Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            try{
                return $this->login_auth($request);
            }catch(\Exception $e){
                return $this->json('0','系统错误');
            }
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }

    /**
     * 登录接口（用户密码登录）
     * @param $username 用户名（手机号）
     * @param $passwrod 密码
     * @return {"status":1,"message":"","data":{"expire":"2016-01-07 15:24:00","sign":"09ceb2126fc8ba67947921163c3c68fc"}}
     */
    public function login_auth(Request $request){
        /*验证用户信息*/
        // $customAttr = [
        //     'auth_type' => '授权类型',
        //     // 'open_id' => '',
        //     // 'access_token' => '',
        //     'nick_name' => '昵称',
        //     'avatar' => '头像',
        // ];
        // $this->validate($request, [
        //     'auth_type' => 'required',
        //     'nick_name' => 'required',
        //     'avatar' => 'required',
        // ],[ ], $customAttr);

        $auth_type = $request->input('auth_type');
        $nick_name = trim($request->input('nick_name'));
        $avatar = $request->input('avatar');
        $open_id = $request->input('open_id');
        $access_token = $request->input('access_token');
        $auth_info = UserComponent::get_auth_info($access_token,$open_id,$auth_type,$request->input('apptype'));
        if (empty($auth_info) || isset($auth_info['errcode'])) {
            return $this->json('0','授权登陆失败，未获取到用户个人信息'.$auth_info['errmsg']);
        }

        $app_login_time = date('Y-m-d H:i:s',time());
        if (strtolower($auth_type)) {
            $open_id_name = ($auth_type == 'wechat')?'wechat_openid':'qq_openid';
            if( $user = UserModel::where($open_id_name,$open_id)->first() ){
                $user->app_login_time = $app_login_time;
                $user->app_type = $request->input('apptype');
                $user->saveOrFail();

                $user_id = $user->user_id;
                // $user_token = UserComponent::get_token($user->phone,$user->password,$user->app_login_time,$request->input('apptype'));
            }else{
                $user = new UserModel();
                $user->$open_id_name = $open_id;
                $user->app_login_time = $app_login_time;
                $user->app_type = $request->input('apptype');
                $user->saveOrFail();
                
                $user_id = $user->user_id;
            }
        }else{
            return $this->json('0','授权类型出错，授权失败');
        }

        if($user_id){
            $user_token = UserComponent::get_token($user->phone,$user->password,$user->app_login_time,$request->input('apptype'));

            $userAccount = UserAccountModel::firstOrCreate(['user_id'=>$user_id]);
            $userProfile = UserProfileModel::firstOrNew(['user_id'=>$user_id]);
            $userSetting = UserSettingModel::select(['lon','lat','city'])->where('user_id',$user_id)->first();
            if (!$userSetting) {
                $userSetting = new UserSettingModel;
                $userSetting->user_id = $user_id;
                $userSetting->save();
                $city = $userSetting->city;
                $lon = $userSetting->lon;
                $lat = $userSetting->lat;
            }else{
                $city = '上海';
                $lon = '121.487899';
                $lat = '31.249162';
            }

            $user_avatar = $userProfile->avatar?$userProfile->avatar:$auth_info['headimgurl'];
            $user_nick_name = $userProfile->nick_name?$userProfile->nick_name:$auth_info['nickname'];

            $userProfile->user_id = $user_id;
            $userProfile->avatar = $user_avatar;
            $userProfile->nick_name = $user_nick_name;
            $userProfile->gender = $auth_info['sex'];
            $status = $userProfile->saveOrFail();
        }else{
            return $this->json('0','用户信息保存失败');
        }

        // $return['status'] = '1';
        // $return['message'] = '登录成功';
        $other['user_token'] = $user_token;
        $other['user_id'] = $user_id;
        $other['has_profile'] = '0';
        $other['avatar'] = $user_avatar;
        $other['city'] = $city;
        $other['lon'] = $lon;
        $other['lat'] = $lat;

        // 向融云注册token
        if ($user_id) {
            // $userProfile = UserComponent::get_base_info($user_id);
            $message_token = RongCloudComponent::register($user_id,$user_nick_name,$user_avatar);
            
            $other['user_base_info'] = $userProfile->toArray();
            $other['message_token'] = $message_token;
            return $this->json('1','','',$other);
        }else{
            return $this->json('0','请求参数错误');
        }
    }
}
